package com.cyy.view.search

import cn.hutool.json.JSONUtil
import com.cyy.model.GmodelModel
import com.cyy.view.GenEvent
import com.jfinal.kit.Kv
import com.jfinal.plugin.activerecord.Db
import com.jfinal.plugin.activerecord.Record
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File

class SQLSearchTab : View("My View") {
    val gm: GmodelModel by inject()
    // 查询语句
    val sql = stringProperty()

    val wbtmpl = stringProperty()
    override val root = form() {
        fieldset {
            field("选择模板文件") {
                button("...") {
                    action {
                        val projectPath = gm.curProjectPath.value

                        val efset = arrayOf(FileChooser.ExtensionFilter("选择模板文件", "*.*"))

                        val fnset = chooseFile("选择模板文件", efset, FileChooserMode.Single) {
                            // p初始目录为当前项目目录
                            initialDirectory = File(projectPath)
                        }
                        if (fnset.isNotEmpty()) {
                            wbtmpl.value = "${fnset.first()}"
                        }
                    }
                }
                textfield(wbtmpl) {
                    text = "${gm.curProjectPath.value}/doc/tmpl/view/index.html"
                }
            }
            field("SQL") {
                textarea(sql) {
                    text = "select * from user"
                }
            }
            button("查询") {
                action {
                    searchBySql(sql.value)
                }
            }
            button("CRUD") {
                action {

                    exeSql(sql.value.trim())
                }
            }
        }
    }

//    fun saveSearch(sql: String) {
//
//    }

    fun searchBySql(sql: String) {
        val kv = Kv.create()
        try {
            val ret = Db.use().find(sql)
            // keys 为要查询的列名
            val keys = JSONUtil.parseObj(ret[0].toString()).keys
            kv.set("ret", ret).set("keys", keys)
        } catch (e: Exception) {
            println("search failed : ${e}")
            fire(GenEvent("search failed : ${e}"))
        }
        gm.tplStringOut.value = gm.engine.value.getTemplate(wbtmpl.value).renderToString(kv)
    }

    fun exeSql(sql: String) {
//        var ret:List<Record>
        var ret: Any
        println(sql)
        if (sql.startsWith("select".toLowerCase())) {
            ret = Db.use().find(sql) as List<Record>
            println(ret.toString())
        } else if (sql.startsWith("update".toLowerCase())) {
            // update user set name='jj' where age='1'
            ret = Db.use().update(sql)
            println(ret.toString())
        } else if (sql.startsWith("insert".toLowerCase())) {
            // insert into user(name,age) values('j2',12)
//            ret = Db.use().batch(sql.splitToSequence(";").toList(),1000)
            ret = Db.use().update(sql)
            println(ret.toString())
        } else if (sql.startsWith("create".toLowerCase())) {
            // insert into user(name,age) values('j2',12)
            ret = Db.use().update(sql)
            println(ret.toString())
        }
    }
}
